import React, {useEffect, useState} from 'react';
import {
  DownOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  SmileOutlined
} from '@ant-design/icons';
import {Avatar, Button, Dropdown, Layout, Menu, Space, MenuProps, Modal, Form, Input, message} from 'antd';
const { Header, Content, Footer, Sider } = Layout;
import {theme} from "antd/lib";
import {connect, history, Link} from "umi";
import md5 from 'crypto-js/md5';

import menus from '../../config/routes';
import LockModal from "@/pages/lock/components/LockModal";

const Main = (props) => {
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  const {login: {userInfo, roleId}, dispatch} = props
  const [open, setOpen] = useState(false)
  const [lockVisible, setLockVisible] = useState(false)

  useEffect(() => {
    dispatch({
      type: 'login/getUserInfo',
    })
    if(window.location.pathname === '/') {
      history.push("/main")
    }
  }, [])

  useEffect(() => {
    dispatch({
      type: 'login/getRoleId',
    }).then((e) => {
      // history.listen((location, action) =>{
      if(e !== 42 && location.pathname === '/users') {
        history.push("/main")
        message.error("无权限访问!")
      }
      // })
    })
  }, [])

  const {confirm} = Modal

  const logout = () => {
    confirm({
      content: '你确定要退出登录吗？',
      onOk() {
        dispatch({
          type: 'login/logout',
        })
      },
      onCancel() {},
      okText: '确定',
      cancelText: '取消',
    })
  }

  const handleChange = () => {
    setOpen(true)
  }

  const handleLock = () => {
    setLockVisible(true)
  }

  const handleClose = () => {
    setLockVisible(false)
  }

  const onLockFinish = (values) => {
    dispatch({
      type: "login/setScreenCode",
      payload: {
        password: md5(values.password).toString(),
      },
    })
    history.push('/lock')
    setLockVisible(false)
  }

  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <Link to={{pathname: '/userInfo', state: {id: userInfo.id}}}>个人中心</Link>
      ),
    },
    {
      key: '2',
      label: (
        <a onClick={handleLock}>锁定屏幕</a>
      ),
    },
    {
      key: '3',
      label: (
        <a onClick={handleChange}>
          修改密码
        </a>
      ),
    },
    {
      key: '4',
      label: (
        <a onClick={logout}>
          退出登录
        </a>
      ),
    },
  ];

  const [form] = Form.useForm()

  const onOk = () => {
    form.submit();
  };

  const onFinish = async (values) => {
    if(values.newPassword !== values.confirmPassword) {
      message.error("新密码和确认密码不一致")
    } else {
      const code = await dispatch({
        type: 'login/changePassword',
        payload: values,
      })
      if(code === 200) {
        message.success("修改成功")
        setOpen(false)
        form.resetFields()
      } else {
        message.error("旧密码错误")
      }
    }
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <Layout>
      <Sider
        trigger={null} collapsible collapsed={collapsed}
        style={{background: "#47484a"}}
      >
        <div style={{paddingTop: "10px", paddingLeft: "10px", paddingBottom: "12px", display: "flex", alignItems: "center"}}>
          <Link to="/main"><img width="50px" src="http://127.0.0.1:9000/spzx-bucket/pictures/logo.jpg"/></Link>
          <div style={{color: "white", fontSize: "20px", marginLeft: "20px"}}>白兰培训</div>
        </div>
        <div className="demo-logo-vertical" />
        <Menu theme="dark" style={{background: "#111010"}} mode="inline" defaultSelectedKeys={window.location.pathname !== "/" ? window.location.pathname.slice(1, window.location.pathname.length) : 'main'}>
          {menus.map(route => {
            if(route.key === 'home') {
              return route.routes.map(children => {
                return (
                  !children.ignore ?
                    (children.needRoleId.includes(roleId)) && (<Menu.Item key={children.key} icon={React.createElement(children.icon)}><Link to={{pathname: children.path, state: {roleId: roleId, userInfo: userInfo}}}>{children.title}</Link></Menu.Item>) : null
                )
              })
            }

          })}
        </Menu>
      </Sider>
      <Layout>
        <Header style={{ padding: 0, background: colorBgContainer }}>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}
          />
          <Space style={{float: "right", marginRight: "30px"}}>
            <Dropdown placement="bottom" menu={{ items }} arrow>
              <a onClick={(e) => e.preventDefault()}>
                <Space >
                  <Avatar size={50} src={userInfo.avatar} />
                  <Space style={{fontSize: "large"}}>
                    {userInfo.name}
                  </Space>
                  <DownOutlined />
                </Space>
              </a>
            </Dropdown>
          </Space>

        </Header>
        <Content style={{ margin: '24px 16px 0' }}>
          <div
            style={{
              // padding: 24,
              minHeight: 733,
              background: "#F3F3F3FF",
              borderRadius: borderRadiusLG,
            }}
          >
            {props.children}
          </div>
        </Content>
        <Footer style={{ textAlign: 'center' }}>
          Michelia ©{new Date().getFullYear()} Created by Crocodile
        </Footer>
      </Layout>
      <LockModal visible={lockVisible} closeHandler={handleClose} userInfo={userInfo} onFinish={onLockFinish}/>
      <Modal
        title="修改密码"
        open={open}
        onOk={onOk}
        onCancel={() => setOpen(false)}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          labelCol={{span: 4}}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item label="旧密码" name="oldPassword" rules={[{ required: true, message: '请输入旧密码!' }]}>
            <Input/>
          </Form.Item>
          <Form.Item label="新密码" name="newPassword" rules={[{ required: true, message: '请输入新密码!' }]}>
            <Input/>
          </Form.Item>
          <Form.Item label="确认密码" name="confirmPassword" rules={[{ required: true, message: '请输入确认密码!' }]}>
            <Input/>
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

const mapStateToProps = ({login}) => {
  return {
    login,
  }
}

export default connect(mapStateToProps)(Main)
